<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { createRoleApi, delRoleApi, editRoleApi, getRoleListApi, changeStatusApi } from '@/api/role'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElMessageBox, ElSwitch, ElTag } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  immediate: true,
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getRoleListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total
    }
  }
})

const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('role.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('role.rolename')
  },
  {
    field: 'status',
    label: t('menu.status'),
    slots: {
      default: (data: any) => {
        const handleChangeStatus = (row: Record<string, any>) => {
          ElMessageBox.confirm(
            `是否确认状态流转为${row.status === 1 ? '启用' : '禁用'}？`,
            t('purchase.logistics.tips'),
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(async () => {
              try {
                const resp = await changeStatusApi({
                  ids: [row.id],
                  status: row.status
                })
                if (resp.code === 0) {
                  ElMessage.success(t('market.industryNews.statusMsg'))
                  await getList()
                }
              } catch (e) {
                await getList()
              }
            })
            .catch(() => {
              row.status = row.status === 1 ? 0 : 1
            })
        }
        return (
          <ElSwitch
            v-model={data.row.status}
            active-value={1}
            inactive-value={0}
            inlinePrompt
            active-text={t('userDemo.enable')}
            inactive-text={t('userDemo.disable')}
            onChange={() => handleChangeStatus(data.row)}
          />
        )
      }
    }
  },
  {
    field: 'create_time',
    label: t('role.create_time')
  },
  {
    field: 'remark',
    label: t('role.remark')
  },
  {
    field: 'action',
    label: t('action.action'),
    width: 240,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="success" onClick={() => action(row, 'detail')}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <BaseButton type="danger" onClick={() => delMenu(row.id)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('role.rolename'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delMenu = (id: string | number) => {
  ElMessageBox.confirm(t('purchase.logistics.confirmDeletion'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delRoleApi({ id })
      ElMessage.success(t('purchase.logistics.deleteSuccess'))
      await getList()
    })
    .catch(() => {})
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const params = {
        role_id: formData.id,
        auth_ids: formData.auth_ids,
        name: formData.name,
        status: formData.status,
        remark: formData.remark,
        order_range: formData.order_range
      }
      if (actionType.value !== 'edit') delete params.role_id
      const resp =
        actionType.value === 'edit' ? await editRoleApi(params) : await createRoleApi(params)
      if (resp) {
        ElMessage.success(actionType.value === 'edit' ? '更新成功' : '新增成功')
        saveLoading.value = false
        dialogVisible.value = false
        await getList()
      }
    } catch (e) {
      saveLoading.value = false
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="70%" max-height="70vh">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <Detail v-else :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
